﻿using System;
using System.Data;

namespace laohan.Common.Common
{
    /// <summary>
    /// 
    /// </summary>
    public partial class API
    {
        /// <summary>
        /// datatable 转换成实体对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <returns></returns>
        public static T GetEntity<T>(DataTable table) where T : new()
        {
            T entity = new T();

            foreach (DataRow row in table.Rows)
            {
                entity = GetEntity<T>(table, row);
            }

            return entity;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <param name="row"></param>
        /// <returns></returns>
        private static T GetEntity<T>(DataTable table, DataRow row) where T : new()
        {
            T entity = new T();

            foreach (var item in entity.GetType().GetProperties())
            {
                if (!table.Columns.Contains(item.Name))
                {
                    continue;
                }

                if (row[item.Name].GetType().FullName == "System.TimeSpan")
                {
                    item.SetValue(entity, DateTime.ParseExact(row[item.Name].ToString(), "HH:mm:ss", null), null);
                }
                else
                {
                    object value = row[item.Name];
                    Type type = item.PropertyType;

                    if (value == null || DBNull.Value == value)
                    {
                        value = DefaultForType(type);
                    }

                    item.SetValue(entity, Convert.ChangeType(value, type), null);
                }
            }
            return entity;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="targetType"></param>
        /// <returns></returns>
        public static object DefaultForType(Type targetType)
        {
            return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
        }
    }
}